package com.tianyi.wz.walkinggame.biz;

import android.app.Activity;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.FilterWord;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdDislike;
import com.bytedance.sdk.openadsdk.TTAdManager;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAdSdk;
import com.bytedance.sdk.openadsdk.TTAppDownloadListener;
import com.bytedance.sdk.openadsdk.TTNativeExpressAd;
import com.tianyi.wz.walkinggame.views.DislikeDialog;

import java.util.List;

public class CsjBannerBiz implements IBannerBiz {

    private CsjBannerBiz(Activity activity,ViewGroup container, String userId, String codeId){
        mActivity = activity;
        mCodeId = codeId;
        mUserId = userId;
        mContainer = container;
        init();
    }

    private TTAdManager ttAdManager;
    private TTAdNative mTTAdNative;

    private Activity mActivity;
    private ViewGroup mContainer;
    private String mCodeId;
    private String mUserId;
    private Callback callback;

    public void setCallback(Callback callback) {
        this.callback = callback;
    }

    public static CsjBannerBiz getInstance(Activity activity, ViewGroup container, String userId, String codeId){
        CsjBannerBiz biz = new CsjBannerBiz(activity,container,userId,codeId);
        return biz;
    }

    private void init(){
        ttAdManager = TTAdSdk.getAdManager();
        ttAdManager.requestPermissionIfNecessary(mActivity);
        mTTAdNative = ttAdManager.createAdNative(mActivity);
    }

    public void showAd(){
        //step4:创建广告请求参数AdSlot,注意其中的setNativeAdtype方法，具体参数含义参考文档
        final AdSlot adSlot = new AdSlot.Builder()
                .setCodeId(mCodeId)
                .setSupportDeepLink(true)
                .setImageAcceptedSize(600,300)
                .setExpressViewAcceptedSize(285,143)
                .setUserID(mUserId)
                .setAdCount(1)
                .setNativeAdType(AdSlot.TYPE_BANNER) //请求原生广告时候，请务必调用该方法，设置参数为TYPE_BANNER或TYPE_INTERACTION_AD
                .build();

        //step5:请求广告，对请求回调的广告作渲染处理
        mTTAdNative.loadBannerExpressAd(adSlot, new TTAdNative.NativeExpressAdListener() {
            @Override
            public void onError(int code, String message) {
                //ToastCommon.showToast(mActivity,"load error : " + code + ", " + message);
                Log.e(CsjBannerBiz.class.getName(),"load error : " + code + ", " + message);
            }

            @Override
            public void onNativeExpressAdLoad(List<TTNativeExpressAd> ads) {
                if (ads==null || ads.size() < 1) {
                    return;
                }

                TTNativeExpressAd ad = ads.get(0);
                ad.setSlideIntervalTime(30*1000);
                bindAdListener(ad);
                ad.render();

            }

        });
    }

    private long startTime = 0;

    private boolean mHasShowDownloadActive = false;

    private void bindAdListener(TTNativeExpressAd ad) {

        ad.setExpressInteractionListener(new TTNativeExpressAd.AdInteractionListener() {
            @Override
            public void onAdClicked(View view, int type) {
                //ToastCommon.showToast(mActivity, "广告被点击");
                Log.d(CsjBannerBiz.class.getName(),"广告被点击");
            }

            @Override
            public void onAdDismiss() {
                List<FilterWord> words = ad.getFilterWords();
                if (words == null || words.isEmpty()) {
                    mContainer.removeAllViews();
                }
            }

            @Override
            public void onAdShow(View view, int type) {
                //ToastCommon.showToast(mActivity, "广告展示");
                Log.d(CsjBannerBiz.class.getName(),"广告展示");
                new LogBiz(mActivity).saveAd(mUserId,mCodeId,1);
            }

            @Override
            public void onRenderFail(View view, String msg, int code) {
                Log.e("ExpressView","render fail:"+(System.currentTimeMillis() - startTime));
                //ToastCommon.showToast(mActivity, msg+" code:"+code);
                Log.d(CsjBannerBiz.class.getName(),msg+" code:"+code);
            }

            @Override
            public void onRenderSuccess(View view, float width, float height) {
                Log.e("ExpressView","render suc:"+(System.currentTimeMillis() - startTime));
                //返回view的宽高 单位 dp
                //ToastCommon.showToast(mActivity, "渲染成功");
                Log.d(CsjBannerBiz.class.getName(),"渲染成功");
                mContainer.removeAllViews();
                mContainer.addView(view);
                if(callback!=null){
                    callback.call();
                }
            }

        });
        //dislike设置
        bindDislike(ad,false);
        if (ad.getInteractionType() != TTAdConstant.INTERACTION_TYPE_DOWNLOAD){
            return;
        }

        ad.setDownloadListener(new TTAppDownloadListener() {
            @Override
            public void onIdle() {
                //ToastCommon.showToast(mActivity, "点击开始下载");
                Log.d(CsjBannerBiz.class.getName(),"点击开始下载");
            }

            @Override
            public void onDownloadActive(long totalBytes, long currBytes, String fileName, String appName) {
                if (!mHasShowDownloadActive) {
                    mHasShowDownloadActive = true;
                    //ToastCommon.showToast(mActivity, "下载中，点击暂停");
                    Log.d(CsjBannerBiz.class.getName(),"下载中，点击暂停");
                }
            }

            @Override
            public void onDownloadPaused(long totalBytes, long currBytes, String fileName, String appName) {
                //ToastCommon.showToast(mActivity, "下载暂停，点击继续");
                Log.d(CsjBannerBiz.class.getName(),"下载暂停，点击继续");
            }

            @Override
            public void onDownloadFailed(long totalBytes, long currBytes, String fileName, String appName) {
                //ToastCommon.showToast(mActivity,  "下载失败，点击重新下载");
                Log.d(CsjBannerBiz.class.getName(),"下载失败，点击重新下载");
            }

            @Override
            public void onInstalled(String fileName, String appName) {
                //ToastCommon.showToast(mActivity,  "安装完成，点击图片打开");
                Log.d(CsjBannerBiz.class.getName(),"安装完成，点击图片打开");
            }

            @Override
            public void onDownloadFinished(long totalBytes, String fileName, String appName) {
                //ToastCommon.showToast(mActivity,  "点击安装");
                Log.d(CsjBannerBiz.class.getName(),"点击安装");
            }
        });
    }


    private void bindDislike(TTNativeExpressAd ad, boolean customStyle) {
        if (customStyle) {
            //使用自定义样式
            List<FilterWord> words = ad.getFilterWords();
            if (words == null || words.isEmpty()) {
                return;
            }

            final DislikeDialog dislikeDialog = new DislikeDialog(mActivity, words);
            dislikeDialog.setOnDislikeItemClick((filterWord) -> {
                    //屏蔽广告
                    Log.d(CsjBannerBiz.class.getName(), "点击 " + filterWord.getName());
                    //用户选择不喜欢原因后，移除广告展示
                    mContainer.removeAllViews();
            });
            ad.setDislikeDialog(dislikeDialog);
            return;
        }
        //使用默认模板中默认dislike弹出样式
        ad.setDislikeCallback(mActivity, new TTAdDislike.DislikeInteractionCallback() {
            @Override
            public void onSelected(int position, String value) {
                Log.d(CsjBannerBiz.class.getName(), "点击 " + value);
                //用户选择不喜欢原因后，移除广告展示
                mContainer.removeAllViews();
                mContainer.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT));
            }

            @Override
            public void onCancel() {
                Log.d(CsjBannerBiz.class.getName(), "点击取消 ");
            }
        });
    }

}
